package com.yiquan.user.service;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.aliyun.oss.OSS;
import com.yiquan.user.client.CommentClient;
import com.yiquan.user.client.VideoClient;
import com.yiquan.user.config.AliyunOSSConfig;
import com.yiquan.user.dao.db.UserActivityDao;
import com.yiquan.user.dao.db.UserIdentifyDao;
import com.yiquan.user.dao.db.UserPictureDao;
import com.yiquan.user.dao.es.EsUserDao;
import com.yiquan.user.pojo.ApplyUpdateUserDTO;
import com.yiquan.user.pojo.UserActivity;
import com.yiquan.user.pojo.UserPicture;
import entity.PageResult;
import entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;
import util.IdWorker;

import com.yiquan.user.dao.db.UserDao;
import com.yiquan.user.pojo.User;
import util.ObjectUtils;

/**
 * 服务层
 *
 * @author Administrator
 */
@Service
@Slf4j
public class UserService {

    private static final Integer USER_PIC_STATUS_NORMAL = 1;

    private static final String APP_NAME = "yi_quan/picture";
    @Autowired
    private UserDao userDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;

    @Autowired
    private UserPictureDao userPictureDao;

    @Autowired
    private UserActivityDao userActivityDao;
    @Autowired
    private UserIdentifyDao userIdentifyDao;

    @Autowired
    private EsUserDao esUserDao;

    @Autowired
    private VideoClient videoClient;

    @Autowired
    private CommentClient commentClient;

    private static final String[] PICTURE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".png"};

    private static final String USER_MODULE_ID = "USER_MODULE_ID";



    /**
     * 获取用户id (20000000-29999999)
     *
     * @return
     */
    public Long getUniqueId() {
        redisTemplate.opsForValue().setIfAbsent(USER_MODULE_ID, 20000000L);
        Long temporaryUserId = redisTemplate.opsForValue().increment(USER_MODULE_ID);
        return temporaryUserId;
    }

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<User> findAll() {
        return userDao.findAll();
    }


    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<User> findSearch(Map whereMap, int page, int size) {
        Specification<User> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return userDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<User> findSearch(Map whereMap) {
        Specification<User> specification = createSpecification(whereMap);
        return userDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public User findById(Long id) {
        return userDao.findById(id).get();
    }

    /**
     * 增加
     *
     * @param user
     */
    public void add(User user) {
        user.setUser_id(getUniqueId());
        user.setCreate_date(new Date());

        user.setNick_name(user.getUsername() == null ? "YQ" + RandomUtils.nextInt(10000000, 99999999) : user.getNick_name());
        user.setFan_nums(0);
        user.setFollow_nums(0);
        user.setWorks_nums(0);
        user.setUser_type("N");
        user.setStatus("0");
        user.setBirthday(new Date());
        /**
         * BCryptPasswordEncoder加密
         */
        user.setPassword(encoder.encode(user.getPassword()));
        userDao.save(user);
    }

    /**
     * 修改
     *
     * @param user
     */
    public void update(User user) {
        userDao.save(user);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(Long id) {
        User user = userDao.findById(id).get();
        user.setStatus("D");
        userDao.deleteById(id);

    }


    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<User> createSpecification(Map searchMap) {

        return new Specification<User>() {

            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                if (StringUtils.isNotBlank((String) searchMap.get("userId"))) {
                    predicateList.add(cb.equal(root.get("user_id").as(Long.class), Long.parseLong((String) searchMap.get("userId"))));
                }
                // 用户名
                if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                    predicateList.add(cb.like(root.get("username").as(String.class), "%" + (String) searchMap.get("username") + "%"));
                }
                //昵称
                if (searchMap.get("nickname") != null && !"".equals(searchMap.get("nickname"))) {
                    predicateList.add(cb.like(root.get("nick_name").as(String.class), "%" + (String) searchMap.get("nickname") + "%"));
                }
                // 性别
                if (searchMap.get("sex") != null && !"".equals(searchMap.get("sex"))) {
                    predicateList.add(cb.like(root.get("sex").as(String.class), "%" + (String) searchMap.get("sex") + "%"));
                }
                // 头像
                if (searchMap.get("avatar") != null && !"".equals(searchMap.get("avatar"))) {
                    predicateList.add(cb.like(root.get("avatar").as(String.class), "%" + (String) searchMap.get("avatar") + "%"));
                }
                // 用户类型
                if (searchMap.get("user_type") != null && !"".equals(searchMap.get("user_type"))) {
                    predicateList.add(cb.like(root.get("user_type").as(String.class), "%" + (String) searchMap.get("user_type") + "%"));
                }
                if (StringUtils.isNotBlank((String) searchMap.get("startCreateDate")) && StringUtils.isNotBlank((String) searchMap.get("endCreateDate"))) {
                    predicateList.add(cb.between(root.get("create_date").as(String.class), (String) searchMap.get("startCreateDate"), (String) searchMap.get("endCreateDate")));
                }
                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }

    public User findByUserId(Long userId) {
        User user = userDao.findUserByUserId(userId);
        Integer thumbs = (Integer) videoClient.getUserVideoTotalThumbs(userId).getData();
        user.setThumbs(thumbs);
        return user;
    }

    public void updateUserByUserId(User user, Long userId) {
        User userOrigin = this.findByUserId(userId);
        ObjectUtils.copyPropertiesIgnoreNull(user, userOrigin);
        this.update(userOrigin);
    }

    public void updateUserById(User user, Long id) {
        User userOrigin = this.findById(id);
        ObjectUtils.copyPropertiesIgnoreNull(user, userOrigin);
        this.update(userOrigin);
    }

    public void deleteByUserId(Long userId) {
        User user = this.findByUserId(userId);
        user.setStatus("D");
        this.update(user);
    }

    public String uploadPicture(MultipartFile multipartFile, Long userId, String pic_type) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        boolean isLegal = false;
        for (String type : PICTURE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }
        if (!isLegal) {
            return null;
        }
        String endpoint = aliyunOSSConfig.getEndpoint();
        // 创建OSSClient实例。
        OSS ossClient = null;
        try {
            ossClient = aliyunOSSConfig.ossClient();//获取客户端实例
            InputStream inputStream = multipartFile.getInputStream();//获取文件输入流
            String originalFilename = multipartFile.getOriginalFilename();//获取原文件名
            String suffix = null;//得到文件后缀名
            if (originalFilename != null) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String bucketName = aliyunOSSConfig.getBucketName();//获取存储桶名
            String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());//创建日期目录

            String newFileName = idWorker.nextId() + suffix;//新文件名
            String fileUrl = APP_NAME + "/" + dateDir + "/" + newFileName;//阿里云的存储路径
            //      填写Byte数组。
            //		byte[] content = "Hello OSS".getBytes();
            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(bucketName, fileUrl, inputStream);

            String picPath = "https://" + bucketName + "." + endpoint + "/" + fileUrl;

            //文件入库
            UserPicture userPicture = new UserPicture();
            userPicture.setPic_id(getUniqueId());
            userPicture.setUser_id(userId);
            userPicture.setPic_path(picPath);
            userPicture.setCreate_date(new Date());
            userPicture.setPic_type(pic_type);
            userPicture.setPic_status(USER_PIC_STATUS_NORMAL);
            userPictureDao.save(userPicture);

            return "https://" + bucketName + "." + endpoint + "/" + fileUrl;//返回资源的下载链接
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭OSSClient。
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public boolean uploadAvatar(MultipartFile file, Long userId) {
        String avatar = this.uploadPicture(file, userId, "avatar");
        if (StringUtils.isNotBlank(avatar)) {
            User userByUserId = userDao.findUserByUserId(userId);
            userByUserId.setAvatar(avatar);
            userDao.save(userByUserId);
            return true;
        }
        return false;
    }

    public String uploadBackground(MultipartFile file, Long userId) {
        String background = this.uploadPicture(file, userId, "background");
        if (StringUtils.isNotBlank(background)) {
            User userByUserId = userDao.findUserByUserId(userId);
            userByUserId.setBackground(background);
            userDao.save(userByUserId);
            return background;
        }
        return null;
    }

    public boolean followUser(Long userId, Long followUserId) {
        UserActivity isCancelFollow = userActivityDao.findByFromUserIdAndToUserId(userId, followUserId);
        //查询对方对我的行为记录
        UserActivity dataForMe = userActivityDao.findByFromUserIdAndToUserId(followUserId, userId);
        // 判断是关注还是取消关注
        if (isCancelFollow == null) {
            UserActivity userActivity = new UserActivity();
            userActivity.setFrom_user_id(userId);
            userActivity.setTo_user_id(followUserId);
            userActivity.setActivity(UserActivity.ACTIVITY_FOLLOW);
            userActivity.setLastOperateTime(new Date());
            userActivity.setStatus(0);  //0 unread 1 read
            //查询对方是否关注自己
            if (dataForMe == null) {
                userActivity.setIs_two_way(UserActivity.IS_NOT_TWO_WAY);
            } else {
                userActivity.setIs_two_way(UserActivity.IS_TWO_WAY);
                dataForMe.setIs_two_way(UserActivity.IS_TWO_WAY);
                userActivityDao.save(dataForMe);
            }
            userDao.updateFollowNum(userId, 1);
            userDao.updateFansNum(followUserId, 1);
            userActivityDao.save(userActivity);
            return true;
        } else {
            if (dataForMe == null) {
                userActivityDao.deleteByFromUserIdAndToUserId(userId, followUserId);
            } else {
                dataForMe.setIs_two_way(UserActivity.IS_NOT_TWO_WAY);
                userActivityDao.save(dataForMe);
                userActivityDao.deleteByFromUserIdAndToUserId(userId, followUserId);
            }
            userDao.updateFollowNum(userId, -1);
            userDao.updateFansNum(followUserId, -1);
            return true;
        }

    }

    public boolean isFollowTheUserByUserId(Long userId, Long theUserId) {
        UserActivity userActivity = userActivityDao.findByFromUserIdAndToUserId(userId, theUserId);
        if (userActivity != null) {
            return true;
        }
        return false;
    }

    public void synchronizeUserData() {
        log.info("开始同步用户数据至Es");
        List<User> all = userDao.findAll();
        esUserDao.saveAll(all);
        log.info("同步信息完成");
    }

    public void updateUserWorkNums(Long userId, Integer num) {
        userDao.updateWorksNum(userId, num);
    }

    public PageResult<User> getUserActivity(Integer page, Integer size, Long userId, Integer status) {
        Map map = new HashMap();
        if (userId != null) {
            map.put("userId", userId);
        }
        if (status != null) {
            map.put("status", status);
        }
        Specification<UserActivity> userActivitySpecification = createUserActivitySpecification(map);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        Page<UserActivity> all = userActivityDao.findAll(userActivitySpecification, pageRequest);
        List<User> list = new ArrayList<>();
        for (UserActivity userActivity : all.getContent()) {
            list.add(userDao.findUserByUserId(userActivity.getFrom_user_id()));
        }
        return new PageResult<User>(all.getTotalElements(), list);
    }

    private Specification<UserActivity> createUserActivitySpecification(Map searchMap) {

        return new Specification<UserActivity>() {

            @Override
            public Predicate toPredicate(Root<UserActivity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                if (searchMap.get("userId") != null) {
                    predicateList.add(cb.equal(root.get("to_user_id").as(Long.class), searchMap.get("userId")));
                }

                //昵称
                if (searchMap.get("status") != null) {
                    predicateList.add(cb.equal(root.get("status").as(Integer.class), searchMap.get("status")));
                }

                if (searchMap.get("activity") != null) {
                    predicateList.add(cb.equal(root.get("activity").as(Integer.class), searchMap.get("activity")));
                }

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }

    /**
     * 根据状态
     *
     * @param userId 被关注的人 需要修改状态的人
     * @param status
     */
    public void updateVideoActivityStatus(Long userId, Integer status) {
        userActivityDao.updateVideoActivityStatus(userId, status);
    }

    public String uploadIdentify(MultipartFile file, Long userId) {
        String background = this.uploadPicture(file, userId, "identify");

        return background;
    }

    /**
     * 添加认证申请
     *
     * @param applyUpdateUserDTO
     */
    public void applyUpdateUserType(ApplyUpdateUserDTO applyUpdateUserDTO) {
        applyUpdateUserDTO.setCreate_time(new Date());
        applyUpdateUserDTO.setStatus(0);
        userIdentifyDao.save(applyUpdateUserDTO);
    }

    /**
     * 同意认证
     *
     * @param id
     */
    public void agreeIdentify(Integer id) {
        updateUserIdentify(id, 1);
    }

    /**
     * 不同意认证
     *
     * @param id
     */
    public void disagreeIdentify(Integer id) {
        updateUserIdentify(id, 2);
    }

    /**
     * 更改认证状态
     *
     * @param id
     * @param status
     */
    public void updateUserIdentify(Integer id, Integer status) {
        userIdentifyDao.updateUserIdentifyId(id, status);
        if (status == 1) {
            ApplyUpdateUserDTO applyUpdateUserDTO = userIdentifyDao.findById(id).get();
            Long userId = applyUpdateUserDTO.getUser_id();
            Integer apply_type = applyUpdateUserDTO.getApply_type();
            String userType = null;
            if (apply_type == 1) {
                userType = "N";
            } else {
                userType = "T";
            }
            User user = new User();
            user.setUser_type(userType);
            updateUserByUserId(user,userId);
        }
    }

    public Page<ApplyUpdateUserDTO> listIdentify(Integer page, Integer size, Map map) {
        Specification<ApplyUpdateUserDTO> identifySpecification = createIdentifySpecification(map);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        Page<ApplyUpdateUserDTO> all = userIdentifyDao.findAll(identifySpecification, pageRequest);
        return all;
    }

    private Specification<ApplyUpdateUserDTO> createIdentifySpecification(Map searchMap) {

        return new Specification<ApplyUpdateUserDTO>() {

            @Override
            public Predicate toPredicate(Root<ApplyUpdateUserDTO> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                if (searchMap.get("userId") != null) {
                    predicateList.add(cb.equal(root.get("user_id").as(Long.class), searchMap.get("userId")));
                }

                //昵称
                if (searchMap.get("status") != null) {
                    predicateList.add(cb.equal(root.get("status").as(Integer.class), searchMap.get("status")));
                }

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }

    public void updateUserStatusByUserId(Long userId) {
        User byUserId = findByUserId(userId);
        if ("0".equals(byUserId.getStatus())) {
            byUserId.setStatus("1");
        } else if ("1".equals(byUserId.getStatus())) {
            byUserId.setStatus("0");
        }
        userDao.save(byUserId);

    }

    public void batchDelete(List<Long> userIdList) {
        for (Long aLong : userIdList) {
            User userByUserId = userDao.findUserByUserId(aLong);
            userByUserId.setStatus("D");
            userDao.save(userByUserId);
        }
    }

    public List<Long> getUserActivityUserIdAll(Long userId, Integer status) {
        Map map = new HashMap();
        map.put("userId", userId);
        map.put("status", status);
        Specification<UserActivity> userActivitySpecification = createUserActivitySpecification(map);
        List<Long> userIds = userActivityDao.findAll(userActivitySpecification).stream().map(UserActivity::getFrom_user_id).collect(Collectors.toList());
        return userIds;
    }

    /**
     * 获取好友列表的userId
     *
     * @param userId
     * @param status
     * @return
     */
    public List<Long> getFriendListUserId(Long userId, Integer status) {
        Map map = new HashMap();
        map.put("userId", userId);
        map.put("status", status);
        Specification<UserActivity> userActivitySpecification = createUserActivitySpecification(map);
        List<Long> userIds = userActivityDao.findAll(userActivitySpecification).stream().filter(userActivity -> userActivity.getIs_two_way() == 1).map(UserActivity::getFrom_user_id)
                .collect(Collectors.toList());
        return userIds;
    }

    /**
     * 获取好友列表
     *
     * @param userId
     * @param status
     * @return
     */
    public List<User> getFriendList(Long userId, Integer status) {
        Map map = new HashMap();
        map.put("userId", userId);
        map.put("status", status);
        map.put("activity",1);
        List<User> userList = new ArrayList<>();
        Specification<UserActivity> userActivitySpecification = createUserActivitySpecification(map);
        List<UserActivity> all = userActivityDao.findAll(userActivitySpecification);
        List<Long> userIds =all .stream().filter(userActivity -> userActivity.getIs_two_way() == 1).map(UserActivity::getFrom_user_id)
                .collect(Collectors.toList());
        for (Long id : userIds) {
            userList.add(userDao.findUserByUserId(id));
        }
        return userList;
    }

    public void addUserActivity(UserActivity userActivity) {
        userActivity.setStatus(0);
        userActivity.setLastOperateTime(new Date());
        userActivityDao.save(userActivity);
    }

    /**
     * 获取用户点赞行为
     *
     * @param page
     * @param size
     * @param userId
     * @return
     */
    public Page<UserActivity> getThumbActivity(Integer page, Integer size, Long userId) {
        Map map = new HashMap();
        map.put("status", 0);
        map.put("activity", 6);
        map.put("userId", userId);
        Specification<UserActivity> userActivitySpecification = createUserActivitySpecification(map);
        Map map1 = new HashMap();
        map1.put("status", 0);
        map1.put("activity", 7);
        map1.put("userId", userId);
        Specification<UserActivity> userActivitySpecification1 = createUserActivitySpecification(map1);
        Specification<UserActivity> or = userActivitySpecification1.or(userActivitySpecification);
        PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "lastOperateTime"));//按照时间降序排列
        Page<UserActivity> all = userActivityDao.findAll(or,pageRequest);
        all.getContent().forEach(userActivity -> {
            if (userActivity.getActivity() == 6) {
                Result byVideoId = videoClient.findByVideoId(userActivity.getBiz_no());
                Map data = (Map) byVideoId.getData();
                Long video_uid = null;
                if(data.get("video_uid") instanceof Integer){
                    video_uid = Integer.toUnsignedLong((Integer)data.get("video_uid"));
                }else {
                    video_uid = (Long) data.get("video_uid");
                }
                data.put("isFollow",isFollowTheUserByUserId(userId,video_uid));
                userActivity.setObject(data);
            } else if (userActivity.getActivity() == 7) {
                Result byVideoId = videoClient.findByVideoId(userActivity.getBiz_no());
                Map data = (Map) byVideoId.getData();
                Long video_uid = null;
                if(data.get("video_uid") instanceof Integer){
                    video_uid = Integer.toUnsignedLong((Integer)data.get("video_uid"));
                }else {
                   video_uid = (Long) data.get("video_uid");
                }

                data.put("isFollow",isFollowTheUserByUserId(userId,video_uid));
                userActivity.setObject(data);
            }
            userActivity.setOperateUser(findByUserId(userActivity.getFrom_user_id()));
        });
        List<UserActivity> content = all.getContent();
        return all;
    }

    /**
     * 获取用户评论行为
     *
     * @param page
     * @param size
     * @param userId
     * @return
     */
    public Page<UserActivity> getCommentActivity(Integer page, Integer size, Long userId) {
        Map map = new HashMap();
        map.put("status", 0);
        map.put("activity", 2);
        map.put("userId", userId);
        Specification<UserActivity> userActivitySpecification = createUserActivitySpecification(map);
        Map map1 = new HashMap();
        map1.put("status", 0);
        map1.put("activity", 3);
        map1.put("userId", userId);
        Specification<UserActivity> userActivitySpecification1 = createUserActivitySpecification(map1);
        Specification<UserActivity> or = userActivitySpecification1.or(userActivitySpecification);
        PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "lastOperateTime"));//按照时间降序排列
        Page<UserActivity> all = userActivityDao.findAll(or,pageRequest);
        all.forEach(userActivity -> {
            if (userActivity.getActivity() == 2) {
                Result byVideoId = videoClient.findByVideoId(userActivity.getBiz_no());
                Map data = (Map) byVideoId.getData();
                Long video_uid = null;
                if(data.get("video_uid") instanceof Integer){
                    video_uid = Integer.toUnsignedLong((Integer)data.get("video_uid"));
                }else {
                    video_uid = (Long) data.get("video_uid");
                }
                data.put("isFollow",isFollowTheUserByUserId(userId,video_uid));
                userActivity.setObject(data);
            } else if (userActivity.getActivity() == 3) {
                Result byVideoId = videoClient.findByVideoId(userActivity.getBiz_no());
                Map data = (Map) byVideoId.getData();
                Long video_uid = null;
                if(data.get("video_uid") instanceof Integer){
                    video_uid = Integer.toUnsignedLong((Integer)data.get("video_uid"));
                }else {
                    video_uid = (Long) data.get("video_uid");
                }
                data.put("isFollow",isFollowTheUserByUserId(userId,video_uid));
                userActivity.setObject(data);
            }
            userActivity.setOperateUser(findByUserId(userActivity.getFrom_user_id()));
        });
        List<UserActivity> content = all.getContent();
        return all;
    }

    /**
     * 获取用户aite行为
     *
     * @param page
     * @param size
     * @param userId
     * @return
     */
    public Page<UserActivity> getAiteActivity(Integer page, Integer size, Long userId) {
        Map map = new HashMap();
        map.put("status", 0);
        map.put("activity", 4);
        map.put("userId", userId);
        Specification<UserActivity> userActivitySpecification = createUserActivitySpecification(map);
        Map map1 = new HashMap();
        map1.put("status", 0);
        map1.put("activity", 5);
        map1.put("userId", userId);
        Specification<UserActivity> userActivitySpecification1 = createUserActivitySpecification(map1);
        Specification<UserActivity> or = userActivitySpecification.or(userActivitySpecification);
        PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "lastOperateTime"));//按照时间降序排列
        Page<UserActivity> all = userActivityDao.findAll(or,pageRequest);
        all.forEach(userActivity -> {
            if (userActivity.getActivity() == 4) {
                Result byVideoId = videoClient.findByVideoId(userActivity.getBiz_no());
                Map data = (Map) byVideoId.getData();
                Long video_uid = null;
                if(data.get("video_uid") instanceof Integer){
                    video_uid = Integer.toUnsignedLong((Integer)data.get("video_uid"));
                }else {
                    video_uid = (Long) data.get("video_uid");
                }
                data.put("isFollow",isFollowTheUserByUserId(userId,video_uid));
                userActivity.setObject(data);
            } else if (userActivity.getActivity() == 5) {
                Result byVideoId = videoClient.findByVideoId(userActivity.getBiz_no());
                Map data = (Map) byVideoId.getData();
                Long video_uid = null;
                if(data.get("video_uid") instanceof Integer){
                    video_uid = Integer.toUnsignedLong((Integer)data.get("video_uid"));
                }else {
                    video_uid = (Long) data.get("video_uid");
                }
                data.put("isFollow",isFollowTheUserByUserId(userId,video_uid));
                userActivity.setObject(data);
            }
            userActivity.setOperateUser(findByUserId(userActivity.getFrom_user_id()));
        });
        List<UserActivity> content = all.getContent();
        return all;
    }

    /**
     * 修改密码
     * @param userId
     * @param oldPassword
     * @param newPassword
     */
    public boolean updatePassword(Long userId, String oldPassword, String newPassword) {
        User userByUserId = userDao.findUserByUserId(userId);
        if (encoder.matches(oldPassword,userByUserId.getPassword())){
            userByUserId.setPassword(encoder.encode(newPassword));
            updateUserByUserId(userByUserId,userId);
            return true;
        }else{
            return false;
        }

    }


    /**
     * 查询关注数
     * @param userId
     * @return
     */
//    public Integer countFollowNums(Long userId){
//        userActivityDao.countUserActivitiesByFrom_user_id(userId)
//    }

    /**
     * 查询被关注数（粉丝数）
     * @param userId
     * @return
     */
//    public Integer countBeFollowNums(Long userId){
//
//        userActivityDao.countUserActivitiesByTo_user_id(userId);
//    }
}
